package progress

import (
	"os"
	"promsync/progress/path"
	"strconv"
)

var (
	pid = "/run.pid"
)

type PidManager struct {
}

func (*PidManager) CreatePid() {
	pidFile := getPidPath()
	_, err := os.Stat(pidFile)
	if err == nil {
		panic("进程已启动")
		return
	}

	if os.IsNotExist(err) {
		temp, err := os.Create(pidFile)

		//最后关闭文件
		defer func() {
			err := temp.Close()
			if err != nil {
				panic(err)
			}
		}()

		if err != nil {
			panic(err)
		}
		_, err = temp.WriteString(strconv.Itoa(os.Getpid()))
		if err != nil {
			panic(err)
		}

	}
}

func (*PidManager) RemovePid() {
	pidFile := getPidPath()
	_, err := os.Stat(pidFile)
	if err == nil {
		err = os.Remove(pidFile)
		if err != nil {
			panic(err.Error())
		}
	}

}

func (*PidManager) GetPid() int {
	pidFile := getPidPath()
	_, err := os.Stat(pidFile)
	if err == nil {
		data, errRead := os.ReadFile(pidFile)
		if errRead != nil {
			panic(errRead)
		}
		pid, errRead := strconv.Atoi(string(data))
		if errRead != nil {
			panic(errRead)
		}
		return pid
	}
	return -1
}

func getPidPath() string {
	return path.GetCurrentDir() + pid
}
